var img = "/public/images/pic_160.png"; //imgurl 就是你的图片路径  

// http://api.gpsspg.com/convert/coord/?parameters         经纬度转换位置信息API
// http://api.gpsspg.com/convert/coord/?oid=我的oid&from=0&to=4&latlng=84.21,38.70;22.9621107600,113.9826665700;39.9173698900,116.3489858800

Page({
  data: {
    isGotLoc: 0,
    files: [],
    motto: 'hw',
    userInfo: {},
    //默认未获取地址
    hasLocation: false,
    inputValue: '',
    commomArray: {
      address_name: 'fk',
      new_longitude: '',
      new_latitude: '',
      img_path: '',
    },
    // new_longitude: '',
    // new_latitude: '',

    address_city: '',
    address_description: '',
    canvasWidth: '',
    canvasHeight: ''


  },
  chooseImage: function() {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success: function(res) {
            var ctx = wx.createCanvasContext('photo_canvas');
            var ratio = 2;
            that.setData({
              canvasWidth: res.width,
              canvasHeight: res.height
            })
            while (that.data.canvasWidth > 10000 || that.data.canvasHeight > 10000) {
              that.setData({
                canvasWidth: Math.trunc(res.width / ratio),
                canvasHeight: Math.trunc(res.height / ratio),
              })
              ratio++
            }
            ctx.drawImage(res.path, 0, 0, that.data.canvasWidth, that.data.canvasHeight)
            ctx.draw()
            setTimeout(function() {
              wx.canvasToTempFilePath({
                fileType: 'jpg',
                quality: 0.5,
                canvasId: 'photo_canvas',
                success: function(res) {
                  console.log('下载canvas成功')
                  //转编码base64
                  wx.getFileSystemManager().readFile({
                    filePath: res.tempFilePath, //选择图片返回的相对路径
                    encoding: 'base64', //编码格式
                    success: res => { //成功的回调
                    },
                    fail: function(e) {
                    }
                  })

                  wx.downloadFile({
                    url: res.tempFilePath,
                    success: function(res) {
                      console.log(res);
                      //图片保存到本地
                      wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function(data) {
                          console.log('...');
                        },
                      })
                    },

                    fail: function(err) {
                      console.log(err);
                      if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                        console.log("用户一开始拒绝了，我们想再次发起授权")
                        console.log('打开设置窗口')
                        wx.openSetting({
                          success(settingdata) {
                            console.log(settingdata)
                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                              console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                            } else {
                              console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                            }
                          }
                        })
                      }
                    }
                  })
                },
                fail: function(error) {
                  console.log(error)
                }
              })
            }, 100)
            console.log('that.data.img_path')
          },
          fail: function(error) {
            console.log(error)
          }
        })

      },
      error: function(res) {
        console.log(res);
      }
    })
  },
  
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  getLocation: function(e) {
    console.log(e)
    var that = this
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        console.log(res)
        that.setData({
          isGotLoc: 1,
          hasLocation: true,
          new_longitude: res.longitude,
          new_latitude: res.latitude,
          location: {
            longitude: res.longitude,
            latitude: res.latitude
          }
        })
        wx.showToast({
          title: '获取坐标成功',
        })
        wx.request({ // 百度地图API，将微信获得的经纬度传给百度，获得城市等信息
          url: 'https://api.map.baidu.com/geocoder/v2/?ak=GAKrXdS2lPhNejYKnvfalheyoiTqcnWG&location=' + that.data.new_latitude + ',' + that.data.new_longitude + '&output=json&coordtype=wgs84ll',
          data: {},
          header: {
            'Content-Type': 'application/json'
          },
          success: function(res) {
            console.log(res.data.result);
            console.log(res.data.result.addressComponent.city + res.data.result.addressComponent.district);
            console.log(res.data.result.sematic_description);
            that.setData({
              address_city: res.data.result.addressComponent.city + res.data.result.addressComponent.district,
              address_description: res.data.result.sematic_description
            })

          },
          fail: function() {
            // fail
          },
        })

      }
    })


  },
  //提交位置信息
  reg: function(e) {
    console.log(this.data.new_longitude, this.data.new_latitude, )
    var ADD_data = {
      "name": this.data.inputValue,
      "lon": this.data.new_longitude,
      "lat": this.data.new_latitude,
    };
    wx.req('locationAdd', ADD_data, '上传中').then(res => {
      wx.navigateBack({ delta: 1 })
      wx.toast('上传成功')
    })
  },
  //根据经纬度在地图上显示
  openLocation: function(e) {
    console.log("openLocation", e)
    var value = e.detail.value
    wx.openLocation({
      longitude: Number(value.longitude),
      latitude: Number(value.latitude),
      name: this.data.address_city, // 位置名
      address: this.data.address_description, // 地址详情说明
    })
  },

  bindKeyInput: function(e) {
    this.setData({
      inputValue: e.detail.value,
    })
    //console.log(inputValue)
  },

});